<template>
  <div class="approval-page">
    <!-- 左侧信息列 -->
    <div class="left-column">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <h3 class="card-title">基本信息</h3>
        <ul class="info-list" v-if="checkoutDtoInfo">
          <li>
            <span class="label">单据编号</span>
            <span class="value">{{ checkoutDtoInfo.checkoutNo }}</span>
          </li>
          <li>
            <span class="label">老人姓名</span>
            <span class="value">{{ checkoutDtoInfo.name }}</span>
          </li>
          <li>
            <span class="label">老人身份证号</span>
            <span class="value">{{ checkoutDtoInfo.idCardNo }}</span>
          </li>
          <li>
            <span class="label">联系方式</span>
            <span class="value">{{ checkoutDtoInfo.contact }}</span>
          </li>
          <li>
            <span class="label">费用期限</span>
            <span class="value">{{
                checkoutDtoInfo.stayStart?.slice(0,10) || ''
              }} —— {{
                checkoutDtoInfo.stayEnd?.slice(0,10) || ''
              }}</span>
          </li>
          <li>
            <span class="label">护理等级</span>
            <span class="value">等级{{ checkoutDtoInfo.careLevel }}</span>
          </li>
          <li>
            <span class="label">入住床位</span>
            <span class="value">{{ checkoutDtoInfo.bedNo }}床位</span>
          </li>
          <li>
            <span class="label">签约合同</span>
            <span class="value">
              {{ checkoutDtoInfo.name ? checkoutDtoInfo.name + "的入住合同" : '暂无合同' }}
              <a v-if="checkoutDtoInfo.contract?.agreementUrl" :href="checkoutDtoInfo.contract.agreementUrl" class="view-link" >查看</a>
            </span>
          </li>
          <li>
            <span class="label">养老顾问</span>
            <span class="value">{{ checkoutDtoInfo.consultant }}</span>
          </li>
          <li>
            <span class="label">护理员</span>
            <span class="value">{{ checkoutDtoInfo.caregiverName }}</span>
          </li>
        </ul>
      </div>

      <!-- 申请信息卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">申请信息</h3>
        <ul class="info-list" v-if="checkoutDtoInfo">
          <li>
            <span class="label">退住日期</span>
            <span class="value">{{ checkoutDtoInfo.checkoutTime }}</span>
          </li>
          <li>
            <span class="label">退住原因</span>
            <span class="value">{{ checkoutDtoInfo.checkoutReason }}</span>
          </li>
          <li>
            <span class="label">备注</span>
            <span class="value">{{ checkoutDtoInfo.remark || '无' }}</span>
          </li>
          <li>
            <span class="label">申请人</span>
            <span class="value">{{ checkoutDtoInfo.applicant }}</span>
          </li>
          <li>
            <span class="label">申请时间</span>
            <span class="value">{{ checkoutDtoInfo.applyTime?.slice(0,19) || '' }}</span>
          </li>
        </ul>
      </div>

      <!-- 解除记录卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">解除记录</h3>
        <ul class="info-list" v-if="checkoutDtoInfo.contract">
          <li>
            <span class="label">提交人</span>
            <span class="value">{{ checkoutDtoInfo.contract.terminateBy }}</span>
          </li>
          <li>
            <span class="label">解除日期</span>
            <span class="value">{{ checkoutDtoInfo.contract.terminateDate?.slice(0,10) || '' }}</span>
          </li>
          <li>
            <span class="label">解除协议</span>
            <span class="value">
              {{ checkoutDtoInfo.name ? checkoutDtoInfo.name +"的退住协议" : '暂无协议' }} <a class="view-link" v-if="checkoutDtoInfo.contract?.terminateAgreementUrl" :href="checkoutDtoInfo.contract.terminateAgreementUrl" >查看</a>
            </span>
          </li>
        </ul>
      </div>

      <!-- 账单明细卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">完成账单清算</h3>
        <!-- 顶部提示 -->
        <div class="bill-tip">
          完成欠费缴费和余额退款后，方可完成退住办理
        </div>
        <!-- 欠费分组：使用解析后的billJson数据 -->
        <div class="bill-section" v-if="billJson.unPayBill">
          <div class="section-header">
            欠费
            <!-- 待办数量：过滤后的列表长度 -->
            <span class="todo-count">待办：{{ filteredUnPayMonth.length }}</span>
            <!-- 欠费小计：过滤后的总和 -->
            <span class="total-amount">小计：{{ filteredUnPayTotal.toFixed(2) }}元</span>
          </div>
          <div class="bill-item" v-for="(item, idx) in filteredUnPayMonth" :key="idx">
            <p>账单编号：{{ item.billNo }} <el-button type="text" size="mini">月度账单</el-button></p>
            <p>账单月份：{{ item.billMonth }}</p>
            <p>应付金额：{{ item.payableAmount.toFixed(2) }}元</p>
          </div>
        </div>

        <!-- 余额分组：使用checkoutDtoInfo.balance -->
        <div class="bill-section" style="margin-top: 15px;" v-if="checkoutDtoInfo.balance">
          <div class="section-header">
            余额
            <span class="total-amount">小计：{{ (checkoutDtoInfo.balance.prepaidBalance+refundAmount+billJson?.refundAmount2).toFixed(2) }}元</span>
          </div>
          <div class="bill-item">
            <p>预缴款：{{ checkoutDtoInfo.balance.prepaidBalance.toFixed(2) }}元</p>
            <p>可退押金：{{ billJson?.refundAmount2.toFixed(2) }}元</p>
            <p>可退金额：{{ this.refundAmount}}元</p>
          </div>
        </div>

        <!-- 最终金额提示：基于billJson计算 -->
        <div class="final-amount" v-if="billJson">
          最终退款金额 = 应退 - 欠费 + 余额 = {{ total.toFixed(2) }}元
          <el-button type="default" size="mini" style="margin-left: 10px;" @click="showRefundDialog = true">上传退款凭证</el-button>
        </div>
      </div>
    </div>

    <!-- 右侧操作记录列 -->
    <div class="right-column">
      <!-- 操作记录卡片：接口未返回操作记录，暂保留结构 -->
        <h3 v-if="log.activities" class="card-title">操作记录</h3>
        <ul class="record-list">
          <li v-for="item in log.activities" class="record-item">
            <div class="item-icon">
              <!-- 替换为“发起申请”图标 -->
              <img src="@/assets/images/avatar.jpg" alt="发起申请" />
            </div>
            <div class="item-content">
              <div class="item-desc">({{ log[item.assignee]?.remark }}){{item.name}}</div>
              <div class="item-status"> {{ log[item.assignee]?.nickName }} （已发起）</div>
              <div v-if="log[item.id] " class="approval-opinion">{{log[item.id].fullMessage}}</div>
            </div>
            <div class="item-time">{{item.endTime ? formatDateStr(item.endTime):""}}</div>
          </li>

        </ul>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="btn-area">
      <el-button type="default" @click="goBack">返回</el-button>
      <el-button type="primary" @click="submitApproval">提交</el-button>
    </div>

    <!-- 上传退款凭证弹窗 -->
    <el-dialog
        title="上传退款凭证"
        v-model="showRefundDialog"
        width="800px"
        :close-on-click-modal="false"
    >
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="退款方式" prop="refundWay">
          <el-select v-model="refundForm.refundWay" placeholder="请选择">
            <el-option label="原路退回" value="0"></el-option>
            <el-option label="其他方式" value="1"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="退款凭证" prop="refundVoucher">
          <el-upload
              class="upload-demo"
              action=""
          :auto-upload="false"
              :limit="1"
          :file-list="refundForm.refundVoucher"
          :on-change="handleVoucherChange"
          :before-upload="beforeVoucherUpload"
          :on-remove="handleVoucherRemove"
          accept=".png,.jpg,.jpeg"
          list-type="picture-card"
          >
          <el-icon>
            <Plus />
          </el-icon>
          <div class="el-upload__text">上传</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="退款备注" prop="refundRemark">
          <el-input v-model="refundForm.refundRemark" type="textarea" :maxlength="50" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showRefundDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">确定</el-button>
      </div>
    </el-dialog>

</template>

<script>
import {checkOutDto, getActivityLog, uploadRefundVoucher} from "@/api/check/checkout.js";
import {Plus} from "@element-plus/icons-vue";

export default {
  name: "ApprovalPage",
  components: {Plus},
  data() {
    return {
      log:{},
      billJson: {
        // 初始化默认结构，避免渲染报错
        unPayBill: { month: [], good: [] },
        refundBill: { month: [], good: [] },
        monthBill: {},
        refundAmount2: 0
      },
      checkoutDtoInfo: {},
      showRefundDialog: false, // 控制弹窗显示隐藏
      refundForm: {
        refundWay: "", // 退款方式
        refundVoucher: [], // 退款凭证
        refundRemark: "" // 退款备注
      },


    };
  },
  computed: {
    // 计算欠费小计
    unPayTotal() {
      return this.billJson.unPayBill.month.reduce(
          (sum, item) => sum + (item.payableAmount || 0),
          0
      );
    },
    // 计算最终退款金额：应退 + 余额 - 欠费
    filteredUnPayMonth() {
      const unPayList = this.billJson?.unPayBill?.month || []; // 原始欠费列表
      const allBills = this.checkoutDtoInfo?.bills || []; // 所有账单（用于对账）

      // 过滤逻辑：仅保留“bills中无匹配billNo”或“匹配但billStatus≠1”的欠费记录
      return unPayList.filter(unPayItem => {
        // 找到bills中与当前欠费账单billNo匹配的记录
        const matchedBill = allBills.find(bill => bill.billNo === unPayItem.billNo);
        // 匹配不到 → 保留；匹配到但status≠1 → 保留；匹配到且status=1 → 过滤
        return !matchedBill || matchedBill.billStatus !== "1";
      });
    },

    // 2. 过滤后的欠费小计（基于过滤后的列表计算）
    filteredUnPayTotal() {
      return this.filteredUnPayMonth.reduce(
          (sum, item) => sum + (item.payableAmount || 0),
          0
      );
    },

    // 3. 最终退款金额（基于过滤后的欠费小计计算）
    total() {
      const refundTotal = this.refundAmount;
      // 替换为过滤后的欠费小计
      console.log("过滤后的欠费小计："+refundTotal+ "过滤后的欠费小计："+this.filteredUnPayTotal+ "余额："+this.checkoutDtoInfo?.balance?.arrearsAmount+ "应退小计："+this.billJson.refundAmount2);
      return refundTotal + (this.billJson?.refundAmount2 || 0) - this.filteredUnPayTotal+this.checkoutDtoInfo?.balance?.prepaidBalance;
    },
    refundAmount() {
      // 显式引用 billJson 顶层，确保依赖被追踪（若之前因字段未初始化导致追踪失效）
      if (!this.billJson) return 0;

      // 原计算逻辑
      const amount1 = Number(this.billJson.refundAmount1) || 0; // 去掉 ?.，因已初始化
      const goodSum = this.billJson.refundBill.good.reduce(
          (sum, item) => sum + (Number(item.payableAmount) || 0),
          0
      );

      console.log("refundAmount 计算结果：", amount1 + goodSum); // 验证结果
      return amount1 + goodSum;}
  },
  methods: {
    goBack() {
      this.$router.push("/CollaborationWork/tasking"); // 路由回退
    },
    submitApproval() {
      try {
        const payload = {
          id: this.checkoutDtoInfo.id,
          refundWay: this.refundForm.refundWay,
          refundAmount: (this.billJson?.refundAmount1 || 0) +
              (this.billJson?.refundBill?.good || []).reduce((sum, item) => sum + (item.payableAmount || 0), 0) + (this.billJson?.refundAmount2 || 0)+this.checkoutDtoInfo?.balance?.prepaidBalance,
          refundRemark: this.refundForm.refundRemark,
          refundVoucher: this.refundForm.refundVoucher
        };
        console.log(payload);
        console.log(this.refundAmount);
        uploadRefundVoucher(payload).then(
            res=>{
              if (res.code === 200) {
                this.$message.success("退款凭证上传成功！");
                this.$emit("next");

              } else {
                this.$message.error(res.msg || "上传失败");
              }
            }
        )

      } catch (err) {
        console.error(err);
        this.$message.error("上传接口异常");
      }

    },
    // 处理退款凭证上传变化
    handleVoucherChange(file, fileList) {
      file.url = URL.createObjectURL(file.raw);
      this.refundForm.refundVoucher = fileList.slice(-1); // 只保留最新的一张
    },

    handleVoucherRemove(file, fileList) {
      this.refundForm.refundVoucher = fileList;
    },
    // 退款凭证上传前校验

    // 提交退款信息
    beforeVoucherUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      const isImage = /\.(png|jpg|jpeg)$/.test(file.name.toLowerCase());
      if (!isImage) {
        this.$message.error("请上传PNG、JPG、JPEG类型的图片!");
        return false;
      }
      return true;
    },

    async submitRefund() {
      if (!this.refundForm.refundVoucher.length) {
        this.$message.warning("请先上传退款凭证图片！");


        return;
      }
      this.showRefundDialog = false;
    },
    formatDateStr(dateStr) {
      // 1. 基础校验：判断是否为有效字符串且包含关键符号
      if (!dateStr || typeof dateStr !== 'string' || !dateStr.includes('T')) {
        console.warn('输入不是有效的日期格式（需包含"T"，如2025-10-23T10:42:42.000+08:00）');
        return '';
      }

      // 2. 截取核心部分：年月日（T之前） + 时分秒（T之后、.之前）
      // 例："2025-10-23T10:42:42.000+08:00" → 拆分为 ["2025-10-23", "10:42:42.000+08:00"]
      const datePart = dateStr.split('T')[0]; // 取"T"前的年月日："2025-10-23"
      const timePart = dateStr.split('T')[1].split('.')[0]; // 取"T"后、"."前的时分秒："10:42:42"

      // 3. 重组为 "年月日 时分秒" 格式
      return `${datePart} ${timePart}`;
    },
  },
  mounted() {
    checkOutDto(this.id).then(res => {
      if (res.code === 200) {

        this.checkoutDtoInfo = res.data;
          if(this.checkoutDtoInfo.processStatus==="7"){
            this.$emit("next");
          }
        // 解析billJson字符串，异常处理避免报错
        try {
          this.billJson = JSON.parse(res.data.checkoutBill.billJson) || this.billJson;
        } catch (e) {
          console.error("billJson解析失败：", e);
        }
      }
    });
    getActivityLog(this.id).then( res=>{
      this.log = res.data
      this.log.activities=res.data.activities.reverse()
      console.log(res.data)
      console.log(res)
    })
  },

  props: {
    id: {
      type: [Number,String],
      default: 0,
    },
  },
};
</script>

<style scoped>
.approval-page {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px;
}

.left-column {
  width: 65%;
}

.right-column {
  width: 33%;
}

.info-card,
.record-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
}

/* 标签右对齐样式 */
.info-list li {
  display: flex;
  margin-bottom: 15px;
}

.info-list .label {
  width: 120px;
  text-align: right;
  margin-right: 15px;
  color: #606266;
}

.info-list .value {
  flex: 1;
}

.view-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

/* 账单明细样式 */
.bill-tip {
  background-color: #e6f7ff;
  color: #20a0ff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.bill-section {
  border: 1px dashed #ebeef5;
  padding: 15px;
  background-color: #fafafa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-weight: bold;
}

.badge {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  font-size: 12px;
  margin-right: 8px;
}

.todo-count,
.total-amount {
  font-size: 12px;
  color: #909399;
}

.bill-item {
  border: 1px solid #ebeef5;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fff;
}

.final-amount {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 12px;
  color: #909399;
}

/* 操作记录核心样式（流程线 + 布局） */
.record-list {
  list-style: none;
  padding: 0;
  position: relative; /* 作为伪元素的定位容器 */
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}

/* 垂直主线：连接所有记录项（除第一个），从头像中间穿过 */
.record-item:not(:first-child)::before {
  content: '';
  position: absolute;
  left: 20px; /* 与40px宽图标中心对齐 */
  top: 0;
  height: 100%;
  width: 1px;
  background-color: #dcdcdc;
}

.item-icon {
  margin-right: 12px;
}

.item-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.item-content {
  flex: 1;
}

.item-desc {
  font-weight: 500;
  margin-bottom: 2px;
}

.item-status {
  color: #909399;
  font-size: 12px;
}

/* 审批意见提示框 */
.approval-opinion {
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.item-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap; /* 防止时间换行 */
}

/* 底部按钮 */
.btn-area {
  margin-top: 40px;
  text-align: center;
  width: 100%;
}

.btn-area button {
  margin: 0 10px;
}

/* 弹窗表单样式补充 */
.el-form-item {
  margin-bottom: 20px;
}

.el-upload__tip {
  margin-top: 5px;
  font-size: 12px;
}

.el-textarea__inner {
  resize: none;
}

.dialog-footer {
  text-align: right;
}

</style>